<?php
declare (strict_types=1);

namespace app\user\logic\user;

use app\user\logic\teacher\Teacher;
use app\user\model\user\Personal as PersonalModel;
use app\user\model\user\PersonalData;
use think\Collection;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\db\Raw;

class Personal extends PersonalModel
{

    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function getList()
    {
        // 端别
        $device_type = request()->device_type == 'pc' ? 0 : 1;
        // 条件
        $map   = $this->getListMap($device_type);
        $order = new Raw('d.sort is null,d.sort ASC,a.sort ASC,d.update_time DESC,a.id ASC');
        // 数据
        $list = [];
        // 手机端数据
        if ($device_type) return $this->getAppPersonalData($map, $order);
        // PC端数据
        $joinOn = ' `a`.`id` = `d`.`config_id`';
        $joinOn .= ' AND `d`.`mhm_id` = ' . request()->mhm_id;
        $joinOn .= ' AND `d`.`data_type` = 2';
        $items  = $this->with(['group_title', 'personal_data'])->alias('a')->leftJoin('site_personal_data d', $joinOn)->where($map)->where(function ($query) {
            $query->where('d.status', 1)->whereNull('d.status', 'OR');
        })->field('a.*')->order($order)->select();

        foreach ($items as $item) {
            // var_dump($item->toArray());
            if (!isset($list[$item['group_id']])) {
                // 查询分组信息
                $groupData = app(PersonalData::class)->where('data_type', 1)->where('config_id', $item['group_id'])->where('mhm_id', request()->mhm_id)->findOrEmpty();

                $list[$item['group_id']] = [
                    'group_title' => $groupData->getAttr('title') ?: $item['group_title'],
                    'group_key'   => $item['group_key'],
                    'group_id'    => $item['group_id'],
                    'sort'        => $groupData->getAttr('sort') ?: $item['group_sort'],
                    'list'        => []
                ];
            }
            $personalData = $item->personalData;
            $_item        = [
                'key'   => $item['key'] ?: '',
                'title' => $item['title'],
            ];
            if ($personalData) {
                $_item['title'] = $personalData->title ?: $item['title'];
            }

            $list[$item['group_id']]['list'][] = $_item;
        }

        $list = Collection::make($list)->order('sort', 'asc')->toArray();

        return array_values($list);

        // 排版设置
        // $default = ['line_display_number'=>1];
        // $typeset = SystemConfig::get('site.personal.display', $default);
        // if ($typeset['line_display_number'] == 1) {
        //     // 重组数组
        // $list = $this->arrayGroup($list, 'group_id', ['group_title', 'group_key']);

        // }
    }

    /**
     * 获取列表数据所需条件
     * Author: 亓官雨树 <lucky.max@foxmail.com>
     * Date: 23/09/14
     *
     * @param $device_type
     * @return array
     */
    public function getListMap($device_type)
    {
        $map[] = ['device_type', '=', $device_type];
        // 讲师 - 我的授课
        if (!static::$mid) {
            $map[] = ['key', 'NOT IN', 'my_teach,my_classes'];
        } else {
            $is_teacher = app(Teacher::class)->isTeacher(static::$mid);
            if (!$is_teacher) {
                $map[] = ['key', '<>', 'my_teach'];
                $map[] = ['key', '<>', 'my_classes'];
                $map[] = ['key', '<>', 'correcting'];
                $map[] = ['key', '<>', 'material'];
                $map[] = ['key', '<>', 'my_schedule'];
            }
            // $is_headmaster = app(Teacher::class)->isHeadmaster(static::$mid);
            // if (!$is_headmaster) {
            //     $map[] = ['key', '<>', 'my_classes'];
            // }
        }
        if ($device_type) $map[] = ['key', '<>', 'address'];
        if ($device_type && request()->mhm_sdn) $map[] = ['key', '<>', 'school'];
        return $map;
    }

    /**
     * 手机端个人中心菜单
     * Author: 亓官雨树 <lucky.max@foxmail.com>
     * Date: 23/09/14
     *
     * @param $map
     * @param $order
     * @return array
     */
    public function getAppPersonalData($map, $order)
    {
        $joinOn = ' `a`.`id` = `d`.`config_id`';
        $joinOn .= ' AND `d`.`mhm_id` = ' . request()->mhm_id;
        $joinOn .= ' AND `d`.`data_type` = 2';

        $items = $this->with(['personalData'])->alias('a')->leftJoin('site_personal_data d', $joinOn)->where('a.device_type', 1)->where($map)->where(function ($query) {
            $query->where('d.status', 1)->whereNull('d.status', 'OR');
        })->field('a.id,a.title,a.icon,a.key')->order($order)->select()->toArray();
        foreach ($items as &$item) {
            $item['icon']  = $item['icon_url'] ?: $item['icon'];
            $item['title'] = $item['data_title'] ?: $item['title'];
            if (!$item['status']) unset($item);
        }
        unset($item);

        return $items;
    }

    /**
     * 根据相同字段重组数组
     * Author 亓官雨树<lucky.max@foxmail.com>
     * Date：   2020-05-28
     *
     * @param array  $arr   [原数组]
     * @param string $key   [分组字段]
     * @param array  $field [添加到新数组公用的字段]
     * @return array              [新数组]
     */
    public function arrayGroup($arr, $key, $field = [])
    {
        $map  = [];
        $dest = [];
        foreach ($arr as $ai) {
            if (!array_key_exists($ai->$key, $map)) {
                // 不存在标识，第一次填充
                $child[$key] = $ai->$key;
                // 添加字段
                if (!empty($field)) {
                    foreach ($field as $v) {
                        $child[$v] = $ai->$v;
                    }
                }
                // 相同字段的新数组
                $child['list'] = [$ai];
                $dest[]        = &$child;
                // 当前分组标识
                $map[$ai->$key] = 1;
            } else {
                // 已存在标识
                foreach ($dest as &$group) {
                    if ($group[$key] == $ai->$key) {
                        $group['list'][] = $ai;
                        break;
                    }
                }
            }
        }
        return $dest;
    }

}
